// Fill out your copyright notice in the Description page of Project Settings.


#include "Algorithm/Quadtree/QuadTree.h"
#include "Kismet/KismetMathLibrary.h"

UObject* QuadTreeNode::worldObject = nullptr;

AQuadTree::AQuadTree()
{
	PrimaryActorTick.bCanEverTick = true;
}

void AQuadTree::BeginPlay()
{
	Super::BeginPlay();
	QuadTreeNode::worldObject = GetWorld();
	root = MakeShareable(new QuadTreeNode(FVector::ZeroVector, FVector(height, width, 0), 0));
	GetWorld()->GetTimerManager().SetTimer(timer, this, &AQuadTree::SpawnActors, playRate, true);
	GetWorld()->GetTimerManager().SetTimer(timer2, this, &AQuadTree::ActorsAddVelocity, 2, true);
}

void AQuadTree::Tick(float DeltaTime)
{
	Super::Tick(DeltaTime);
	if (root.IsValid())
	{
		// 更新状态
		root->UpdateState();
		// 判断是否在扫描器的范围内
		root->TraceObjectInRange(traceActor, affectRadianRange);
	}
}

void AQuadTree::SpawnActors()
{
	if (cubeCount < 0)
	{
		GetWorld()->GetTimerManager().ClearTimer(timer);
		return;
	}
	cubeCount--;
	FVector pos = FVector(UKismetMathLibrary::RandomIntegerInRange(-height + 10, height - 10), UKismetMathLibrary::RandomIntegerInRange(-width + 10, width - 10), 11);
	FTransform trans = FTransform(FRotator(0, UKismetMathLibrary::RandomFloatInRange(0, 360), 0), pos, FVector(0.2));
	ABattery* actor = GetWorld()->SpawnActor<ABattery>(BatteryClass, trans);
	if (IsValid(actor))
	{
		objs.Add(actor);
		root->InsertObj(actor);
	}
}

void AQuadTree::ActorsAddVelocity()
{
	for (ABattery* actor : objs)
	{
		actor->GetStaticMeshComponent()->SetPhysicsLinearVelocity(UKismetMathLibrary::RandomUnitVector() * 50);
	}
}
